﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;

namespace BW.Mes.WinForms.BasicData
{
    public partial class SupplierForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _supplierApiBaseUrl = "https://localhost:7274";
        public SupplierForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            
            // 注释掉AddButtons调用，避免动态添加按钮
            // AddButtons();
            SetupGridActionColumn();
            this.Load += SupplierForm_Load;
            this.Shown += SupplierForm_Shown;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;

            // 在构造函数或Load事件后，设置查询区只保留编号、名称和查询按钮
            labelControlCode.Location = new System.Drawing.Point(30, 18);
            labelControlCode.Text = "编号";
            textEditCode.Location = new System.Drawing.Point(70, 15);
            textEditCode.Size = new System.Drawing.Size(100, 28);
            labelControlName.Location = new System.Drawing.Point(180, 18);
            labelControlName.Text = "名称";
            textEditName.Location = new System.Drawing.Point(220, 15);
            textEditName.Size = new System.Drawing.Size(100, 28);
            btnQuery.Location = new System.Drawing.Point(340, 15);
            btnQuery.Size = new System.Drawing.Size(80, 28);

            // 绑定按钮事件
            btnAdd.Click += btnAdd_Click;
            btnEdit.Click += btnEdit_Click;
            btnDelete.Click += btnDelete_Click;
            btnRefresh.Click += btnRefresh_Click;
        }

        private void SupplierForm_Load(object sender, EventArgs e)
        {
            LoadSupplierData();
        }

        private void SupplierForm_Shown(object sender, EventArgs e)
        {
            // 确保按钮在表单显示时可见
            EnsureButtonsVisible();
            
            // 测试按钮是否正确添加
            TestButtonsVisibility();
        }

        private void AddButtons()
        {
            /*
            var btnAdd = new DevExpress.XtraEditors.SimpleButton();
            btnAdd.Location = new System.Drawing.Point(20, 30);
            btnAdd.Name = "btnAdd";
            btnAdd.Size = new System.Drawing.Size(80, 30);
            btnAdd.Text = "新增";
            btnAdd.Visible = true;
            btnAdd.Click += btnAdd_Click;
            this.panelControl1.Controls.Add(btnAdd);

            var btnEdit = new DevExpress.XtraEditors.SimpleButton();
            btnEdit.Location = new System.Drawing.Point(120, 30);
            btnEdit.Name = "btnEdit";
            btnEdit.Size = new System.Drawing.Size(80, 30);
            btnEdit.Text = "修改";
            btnEdit.Visible = true;
            btnEdit.Click += btnEdit_Click;
            this.panelControl1.Controls.Add(btnEdit);

            var btnDelete = new DevExpress.XtraEditors.SimpleButton();
            btnDelete.Location = new System.Drawing.Point(220, 30);
            btnDelete.Name = "btnDelete";
            btnDelete.Size = new System.Drawing.Size(80, 30);
            btnDelete.Text = "删除";
            btnDelete.Visible = true;
            btnDelete.Click += btnDelete_Click;
            this.panelControl1.Controls.Add(btnDelete);

            var btnRefresh = new DevExpress.XtraEditors.SimpleButton();
            btnRefresh.Location = new System.Drawing.Point(320, 30);
            btnRefresh.Name = "btnRefresh";
            btnRefresh.Size = new System.Drawing.Size(80, 30);
            btnRefresh.Text = "刷新";
            btnRefresh.Visible = true;
            btnRefresh.Click += btnRefresh_Click;
            this.panelControl1.Controls.Add(btnRefresh);
            this.panelControl1.Visible = true;
            */
        }

        private void SetupGridActionColumn()
        {
            var actionColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            actionColumn.Caption = "操作";
            actionColumn.Name = "ActionColumn";
            actionColumn.Visible = true;
            actionColumn.VisibleIndex = 10;
            actionColumn.Width = 180;
            actionColumn.MinWidth = 180;
            actionColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            var buttonEdit = actionColumn.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit;
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            buttonEdit.Buttons.Clear();
            var editButton = new DevExpress.XtraEditors.Controls.EditorButton();
            editButton.Caption = "修改";
            editButton.Width = 60;
            buttonEdit.Buttons.Add(editButton);
            var deleteButton = new DevExpress.XtraEditors.Controls.EditorButton();
            deleteButton.Caption = "删除";
            deleteButton.Width = 60;
            buttonEdit.Buttons.Add(deleteButton);
            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
            gridView1.Columns.Add(actionColumn);
        }

        private void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                var supplier = gridView1.GetRow(rowHandle) as SupplierModel;
                if (supplier != null)
                {
                    if (e.Button.Caption == "修改")
                    {
                        var updateForm = new UpdateSupplierForm(supplier);
                        if (updateForm.ShowDialog() == DialogResult.OK)
                        {
                            LoadSupplierData();
                        }
                    }
                    else if (e.Button.Caption == "删除")
                    {
                        var confirm = XtraMessageBox.Show($"确定要删除供应商 '{supplier.SupplierName}' 吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (confirm == DialogResult.Yes)
                        {
                            DeleteSupplier(supplier.Id);
                        }
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var addForm = new AddSupplierForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                LoadSupplierData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var supplier = gridView1.GetRow(selectedRows[0]) as SupplierModel;
            if (supplier == null)
            {
                XtraMessageBox.Show("未获取到供应商信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var updateForm = new UpdateSupplierForm(supplier);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadSupplierData();
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的供应商！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个供应商吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;
            foreach (var rowHandle in selectedRows)
            {
                var supplier = gridView1.GetRow(rowHandle) as SupplierModel;
                if (supplier != null)
                {
                    await DeleteSupplier(supplier.Id);
                }
            }
            LoadSupplierData();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadSupplierData();
        }

        private async void LoadSupplierData()
        {
            try
            {
                var response = await _httpClient.GetAsync($"{_supplierApiBaseUrl}/api/Supplier/GetSupplier");
                var responseContent = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        // 尝试解析为ApiResult格式
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<SupplierListResponse>>(responseContent);
                        if (apiResult != null && apiResult.success == 1 && apiResult.data != null)
                        {
                            gridControl1.DataSource = apiResult.data.pageDatas;
                        }
                        else
                        {
                            // 如果不是ApiResult格式，尝试直接解析
                            var result = JsonConvert.DeserializeObject<SupplierListResponse>(responseContent);
                            if (result != null)
                            {
                                gridControl1.DataSource = result.pageDatas;
                            }
                            else
                            {
                                XtraMessageBox.Show("数据格式错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        
                        gridView1.PopulateColumns();
                        gridView1.BestFitColumns();
                        gridView1.OptionsSelection.MultiSelect = true;
                        gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
                        if (gridView1.Columns.Count > 0)
                            gridView1.Columns[0].VisibleIndex = 0;
                        AfterBindSupplierData();
                    }
                    catch (JsonException ex)
                    {
                        XtraMessageBox.Show($"数据解析错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        // 确保按钮仍然可见
                        EnsureButtonsVisible();
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch
                    {
                        // 如果无法解析错误信息，使用默认错误信息
                    }
                    
                    XtraMessageBox.Show($"获取供应商数据失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    // 确保按钮仍然可见
                    EnsureButtonsVisible();
                }
            }
            catch (HttpRequestException ex)
            {
                XtraMessageBox.Show($"网络连接错误：{ex.Message}", "连接错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 确保按钮仍然可见
                EnsureButtonsVisible();
            }
            catch (TaskCanceledException ex)
            {
                XtraMessageBox.Show("请求超时，请检查网络连接", "超时错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 确保按钮仍然可见
                EnsureButtonsVisible();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // 确保按钮仍然可见
                EnsureButtonsVisible();
            }
        }

        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_supplierApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 调试显示原始响应内容
                Console.WriteLine($"API响应: {responseBody}");

                // 先解析为JObject以便提取内部数据
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                // 假设数组数据在"data"字段中
                if (jsonObject["data"] != null)
                {
                    string dataJson = jsonObject["data"].ToString();
                    Console.WriteLine($"提取的data字段: {dataJson}");
                    return JsonConvert.DeserializeObject<T>(dataJson);
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"获取数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return default;
            }
        }

        private async Task DeleteSupplier(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_supplierApiBaseUrl}/api/Supplier/DeleteSupplier?id={id}", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                
                if (response.IsSuccessStatusCode)
                {
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && apiResult.success == 1)
                        {
                            XtraMessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            string errorMessage = apiResult?.message ?? "删除失败，未知错误";
                            XtraMessageBox.Show($"删除失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (JsonException)
                    {
                        // 如果无法解析为ApiResult格式，则按原逻辑处理
                        XtraMessageBox.Show("删除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch
                    {
                        // 如果无法解析错误信息，使用默认错误信息
                    }
                    
                    XtraMessageBox.Show($"删除失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (HttpRequestException ex)
            {
                XtraMessageBox.Show($"网络连接错误：{ex.Message}", "连接错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (TaskCanceledException ex)
            {
                XtraMessageBox.Show("请求超时，请检查网络连接", "超时错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除异常: {ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public class SupplierModel
        {
            public long Id { get; set; }
            [DisplayName("供应商编号")]
            public string SupplierCode { get; set; }
            [DisplayName("供应商名称")]
            public string SupplierName { get; set; }
            [DisplayName("简称")]
            public string Abbreviation { get; set; }
            [DisplayName("电话")]
            public string Phone { get; set; }
            [DisplayName("地址")]
            public string Address { get; set; }
            [DisplayName("社会信用代码")]
            public string USCC { get; set; }
            [DisplayName("描述")]
            public string SupplierMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("更新时间")]
            public DateTime? UpdatedAt { get; set; }
        }

        public class SupplierListResponse
        {
            public int totalCount { get; set; }
            public List<SupplierModel> pageDatas { get; set; }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindSupplierData()
        {
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
        }

        private void EnsureButtonsVisible()
        {
            // 确保所有按钮都可见
            int buttonCount = 0;
            foreach (Control control in panelControl1.Controls)
            {
                if (control is DevExpress.XtraEditors.SimpleButton)
                {
                    control.Visible = true;
                    buttonCount++;
                    Console.WriteLine($"按钮 '{control.Text}' 设置为可见");
                }
            }
            panelControl1.Visible = true;
            Console.WriteLine($"总共设置了 {buttonCount} 个按钮为可见");
            Console.WriteLine($"panelControl1 可见性: {panelControl1.Visible}");
        }

        private void TestButtonsVisibility()
        {
            Console.WriteLine("=== 测试按钮可见性 ===");
            Console.WriteLine($"panelControl1 控件数量: {panelControl1.Controls.Count}");
            Console.WriteLine($"panelControl1 可见性: {panelControl1.Visible}");
            Console.WriteLine($"panelControl1 大小: {panelControl1.Size}");
            Console.WriteLine($"panelControl1 位置: {panelControl1.Location}");
            
            int buttonCount = 0;
            foreach (Control control in panelControl1.Controls)
            {
                Console.WriteLine($"控件: {control.Name}, 类型: {control.GetType().Name}, 可见性: {control.Visible}, 文本: {control.Text}");
                if (control is DevExpress.XtraEditors.SimpleButton)
                {
                    buttonCount++;
                }
            }
            Console.WriteLine($"找到 {buttonCount} 个按钮");
            Console.WriteLine("=== 测试完成 ===");
        }
    }
}